import router from './router'
import store from './store'
import {Message} from 'element-ui'
import {getRoutes} from '@/api/auth'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import storage from '@/utils/storage'// sessionStorage
// import getPageTitle from '@/utils/get-page-title' // 是否显示路由标题方法

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist  开放路由数组

router.beforeEach(async (to, from, next) => {

  // start progress bar
  NProgress.start()

  // 设置路由标题
  // document.title = getPageTitle(to.meta.title)

  // 获取token
  const hasToken = storage.getItem('token')

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({path: '/'})
      NProgress.done()
    } else {
      // 判断store是否有后台获取的路由
      const hasAddRoutes = store.getters.addRoutes && store.getters.addRoutes.length > 0
      if (hasAddRoutes) {
        next()
      } else {
        try {
          // 调用获取后台返回的路由
          store.dispatch('permission/generateRoutes').then(async () => {
            let addRoutes = store.getters.addRoutes  // 添加的路由
            let routes = store.getters.routes  // 所有的路由

            // 路由更新
            console.log('路由更新', routes)
            router.options.routes = routes

            // 添加路由
            console.log('添加路由', addRoutes)
            router.addRoutes(addRoutes)

            // 获取用户信息
            await store.dispatch('user/profile')
            // 获取用户按钮权限
            await store.dispatch('permission/generatePermissions')

            next({...to, replace: true})
          })

        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    const path = window.location.pathname
    // 没有token
    if (whiteList.indexOf(to.path) !== -1 || path.split('_')[0] == '/public') {
      // 没有token的情况下允许进入开放路由
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
